package com.xyhuo.leetcode.december;

import java.util.ArrayDeque;
import java.util.Deque;

/**
 * 二进制求和
 * https://leetcode.cn/problems/add-binary/
 *
 * @time 2023/12/26
 */
public class AddBinary {

//    public static void main(String[] args) {
//        AddBinary ab = new AddBinary();
//        ab.addBinary("1010", "1011");
//    }

    public String addBinary(String a, String b) {

        char[] aCharArray = a.toCharArray();
        char[] bCharArray = b.toCharArray();

        Deque<Character> deque = new ArrayDeque<>();
        int index = 0;
        int add = 0;
        while (true) {
            if (aCharArray.length - 1 - index < 0 && bCharArray.length - 1 - index < 0) {
                break;
            }
            int oneCount = 0;
            if (aCharArray.length - 1 - index >= 0 && aCharArray[aCharArray.length - 1 - index] == '1') {
                oneCount++;
            }
            if (bCharArray.length - 1 - index >= 0 && bCharArray[bCharArray.length - 1 - index] == '1') {
                oneCount++;
            }
            if (add == 1) {
                oneCount++;
            }
            if (oneCount == 0) {
                deque.addFirst('0');
                add = 0;
            } else if (oneCount == 1) {
                deque.addFirst('1');
                add = 0;
            } else if (oneCount == 2) {
                deque.addFirst('0');
                add = 1;
            } else if (oneCount == 3) {
                deque.addFirst('1');
                add = 1;
            }
            index++;
        }
        if (add == 1) {
            deque.addFirst('1');
        }

        StringBuilder sb = new StringBuilder();
        while (!deque.isEmpty()) {
            Character item = deque.removeFirst();
            sb.append(item);
        }
        return sb.toString();
    }
}
